package com.jiashihui.web.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jiashihui
 * @describe: 拦截器
 * @date 2019/01/18
 */
public class Interceptor implements HandlerInterceptor {

    private long start = System.currentTimeMillis();
    // 在业务处理器处理请求之前被调用
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        start = System.currentTimeMillis();
        // 403表示资源不可用。服务器理解用户的请求，但是拒绝处理它，通常是由于权限的问题
        // httpServletResponse.sendError(403);
        return true;
        //1.equals()函数：主要是区分“比较的字符串” 大小写和长度时候相同，比较的类型可以是Object类型。
        //2.equalsIgnoreCase()函数：比较的参数只能是字符串，这里只要字符串的长度相等，字母的大小写是忽略的。认为A-Z和a-z是一样的。
//        if("GET".equalsIgnoreCase(httpServletRequest.getMethod())){}
//        System.out.println("preHandle...");
//        String requestUri = httpServletRequest.getRequestURI();
//        String contextPath = httpServletRequest.getContextPath();
//        String url = requestUri.substring(contextPath.length());
//        System.out.println("requestUri" + requestUri);
//        System.out.println("contextPath" + contextPath);
//        System.out.println("url" + url);
//        String username = (String) httpServletRequest.getSession().getAttribute("username");
//        if(null == username){
//            // 跳转到登录页面
//            httpServletRequest.getRequestDispatcher("/hello").forward(httpServletRequest, httpServletResponse);
//            return false;
//        }
//        else{
//            return true;
//        }
    }

    // 在业务处理器处理请求完成之后，生成视图之前执行
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("Interceptor cost="+(System.currentTimeMillis()-start));
//        if(modelAndView != null){
//            Map<String, String> map = new HashMap<String, String>();
//            modelAndView.addAllObjects(map);
//        }
    }

    // 在DispatcherServlet完全处理完请求之后被调用，可用于清理资源
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion...");
    }
}
